package controller;

import service.AuthService;
import view.RegisterView;
import view.LoginView;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class RegisterController {
    private final RegisterView view;
    private final AuthService authService;

    public RegisterController(RegisterView view, AuthService authService) {
        this.view = view;
        this.authService = authService;

        view.addRegisterListener(new RegisterListener());
        view.addBackListener(e -> {
            view.dispose();
            LoginView loginView = new LoginView();
            new LoginController(loginView, authService);
            loginView.setVisible(true);
        });
    }

    class RegisterListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String username = view.getUsername();
            String password = view.getPassword();
            boolean isAdmin = view.isAdmin();

            if (username.isEmpty() || password.isEmpty()) {
                JOptionPane.showMessageDialog(view, "用户名和密码不能为空", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (authService.register(username, password, isAdmin)) {
                JOptionPane.showMessageDialog(view, "注册成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                view.dispose();
                LoginView loginView = new LoginView();
                new LoginController(loginView, authService);
                loginView.setVisible(true);
            } else {
                JOptionPane.showMessageDialog(view, "用户名已存在", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}